import axios from 'axios'
import store from '@/store'
import notification from 'ant-design-vue/es/notification'
import { getToken, setToken } from './auth'
import { checkLogin } from '@/utils/authCenter'
// 创建axios实例
const request = axios.create({
  // baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 30000, // 请求超时时间
})

// 异常处理
const errorHanlder = (error) => {
  if (error.response) {
    const data = error.response.data
    // 获取tooken
    const token = getToken()

    if (error.response.status === 403) {
      notification.error({
        message: 'Forbidden',
        description: data.message,
      })
    }

    if (error.response.status === 401) {
      //注销登录
      checkLogin()
    }
  }
  return Promise.reject(error)
}

// requets 拦截
request.interceptors.request.use((config) => {
  const token = getToken()
  // 请求头携带token
  if (token) {
    config.headers['Authorization'] = token
  }

  return config
}, errorHanlder)

// response拦截
request.interceptors.response.use((response) => {
  // 状态码
  const { status, message } = response.data // 根据系统指定的status值
  const oldToken = store.state.user.token
  const newToken = response.config.headers['Authorization']
  if (!oldToken && newToken) {
    setToken(newToken)
    store.commit('user/SET_TOKEN', newToken)
  }
  //blob文件类型的
  if (response.request.responseType == 'blob') {
    return response
  }
  //放开status指定的状态的返回值
  if (status === 0) {
    return response.data
  } else if (status === 101) {
    return response.data
  } else {
    return response.data
  }
  // 其他状态码处理
}, errorHanlder)

export default request
